/**
 * actions.js
 * 2016-03-26
 */

var db = require("../bin/dbutil");

$('/restart', function(form, e){
	console.log('Process - [PID '+process.pid+'] is shuting down and the server will be start a new child process!');
	this.writeHead(302, "Server shutdown!", {Location: "/"});
	this.end();
	process.exit();
});

$('/shutdown', function(form, e){
	console.log('Shutting down the server...');
	this.writeHead(302, "Server reload!", {Location: "/"});
	this.end();
	process.send("SHUTDOWN");
});

$('/hello', function(form, e){
	this.write('hello!');

	this.end();
});

$('/request', function(form, e){
	console.log(JSON.stringify(form.fields));
	this.send({success: true, message: "Operation was successful!"});
	// this.send("OK");
});

$('/',  function(form, e){
	console.log(JSON.stringify(form));
	this.render("welcome", {title: "the new server"});
});

$('/test', function(form, e){
	this.write("queryParams: "+JSON.stringify(e.query));
	this.write("form-data:"+JSON.stringify(form));
	this.end();
});

$('/user/${username}', function(form, e){
	this.write("welcome, "+e.pathvars.username);
	this.end();
});

$('/system/?/view', function(form, e){
	this.write("Path: "+e.url);
	this.end();
});

$('/haha', function(){
	console.log("haha");
	this.end();
});

$('/user/save', function(form, e){
	var chain = this;
	var sql = 'select * from sys_user';
	db.exec(sql, function(err, affect){
		if(err){
			chain.render(500, err);
		}else{
			chain.send({"success": true, "message": "Saved has been successful!", data: affect});
		}
	});
});


